package com.server.common.redis.service;

import cn.hutool.core.util.ArrayUtil;
import com.server.model.all.enums.SystemEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisBlackWhiteListService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 是否是黑名单IP
     * @author LXC
     * @date 2023/2/2 13:34
     */
    public Boolean hasBlackIpAddr(String ipAddr){
        return redisTemplate.opsForSet().isMember(SystemEnum.blackWhiteListStateEnum.BACK.getRedisKey(),
                ipAddr);
    }

    /**
     * 是否是白名单IP
     * @author LXC
     * @date 2023/2/2 13:34
     */
    public Boolean hasWhiteIpAddr(String ipAddr){
        Boolean hasWhite = redisTemplate.hasKey(SystemEnum.blackWhiteListStateEnum.WHITE.getRedisKey());
        if(Boolean.FALSE.equals(hasWhite)){
            return false;
        }
        return redisTemplate.opsForSet().isMember(SystemEnum.blackWhiteListStateEnum.WHITE.getRedisKey(),
                ipAddr);
    }

    /**
     * 获取所有黑或白名单
     * @author LXC
     * @date 2023/2/4 9:09
     */
    public Set<String> getIpAddrList(SystemEnum.blackWhiteListStateEnum stateEnum){
        return redisTemplate.opsForSet().members(stateEnum.getRedisKey());
    }

    /**
     * 获取所有黑或白名单
     *
     * @author LXC
     * @date 2023/2/4 9:09
     */
    public Long addIpAddr(SystemEnum.blackWhiteListStateEnum stateEnum, List<String> ipAddrList){
        if(ObjectUtils.isEmpty(ipAddrList)){
            redisTemplate.expire(stateEnum.getRedisKey(),0L, TimeUnit.SECONDS);
            return 0L;
        }
        return redisTemplate.opsForSet().add(stateEnum.getRedisKey(), ArrayUtil.toArray(ipAddrList,String.class));
    }

}
